<style lang="less" scoped>

</style>

<template>
  <div class="contain drawall">
    <app-head :show="showstate" :title="pagetitle"></app-head>
    <div class="ft14">
      <tab bar-active-color="#23a5a5" defaultColor="#333333" active-color="#23a5a5" :line-width='2' v-model="tabNo">
        <tab-item @on-item-click="tabNo = 0">整车提货</tab-item>
        <tab-item @on-item-click="tabNo = 1">区域提货</tab-item>
      </tab>
    </div>

    <div>
      <div class="car-bbinfo-card">
        <div class="bbno lineb">排车单号：{{data.ATVNo}}</div>
      </div>

      <div class="car-bbinfo-card"  style="position:relative" v-if='tabNo === 1'>
        <div class="bbmain lineb">
          <popup-picker style="z-index:1; background:transparent" :title="AreaPickerTitle" :data="AreaList" v-model="selectedArea" @on-change="getText" :placeholder="'请选择'" :show-name="true"></popup-picker>
          <div style="position:absolute; top:0.2rem; right:0.45rem; font-size:16px; z-index:0; color:#888">{{selectedTextArea}}</div>
        </div>
      </div>

      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <p class="displayflex"><i>配送路线</i><label class="flex1">{{data.routeName}}</label></p>
          <p class="displayflex"><i>承运商</i><label class="flex1">{{data.deliverName}}</label></p>
          <p class="displayflex"><i>派单司机</i><label class="flex1">{{data.driver1Name}}</label></p>
          <p class="displayflex"><i>订单数</i><label class="flex1">{{datas.length}}</label></p>
          <p class="displayflex"><i>总件数</i><label class="flex1">{{data.totalPkgs}}</label></p>
        </div>
      </div>

      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <p class="displayflex"><i>取货地址数</i><label class="flex1">{{data.depAddressList.length}}</label></p>
          <p class="displayflex"><i>送货地址数</i><label class="flex1">{{data.arrivalAddressCount}}</label></p>
          <p class="displayflex"><i>客户数</i><label class="flex1">{{data.cutomerCount}}</label></p>
        </div>
      </div>

      <template v-if="tabNo === 0">
        <div data class="car-bbinfo-card">
          <div data class="bbmain lineb ">
            <div data class="vux-cell-box" v-on:click="showDepAddress=true">
              <div class="weui-cell vux-tap-active weui-cell_access">
                <div class="weui-cell__hd">
                  <label class="weui-label" style="display: block; width: auto;">共计{{data.depAddressList.length}}个取货地址</label>
                </div>
                <div class="vux-cell-primary vux-popup-picker-select-box">
                  <div class="vux-popup-picker-select" style="text-align: right;">
                    <span class="vux-popup-picker-placeholder vux-cell-placeholder">查看</span>
                  </div>
                </div>
                <div class="weui-cell__ft"></div>
              </div>
            </div>
          </div>
        </div>
        <div data class="car-bbinfo-card mb30">
          <div data class="bbmain lineb ">
            <div data class="vux-cell-box" v-on:click="showArrAddress=true">
              <div class="weui-cell vux-tap-active weui-cell_access">
                <div class="weui-cell__hd">
                  <label class="weui-label" style="display: block; width: auto;">共计{{data.arrAddressList.length}}个送货地址</label>
                </div>
                <div class="vux-cell-primary vux-popup-picker-select-box">
                  <div class="vux-popup-picker-select" style="text-align: right;">
                    <span class="vux-popup-picker-placeholder vux-cell-placeholder">查看</span>
                  </div>
                </div>
                <div class="weui-cell__ft"></div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <div class="car-bbinfo-card">
        <div class="bbmain lineb">
          <datetime class="vux-form" :format="'YYYY-MM-DD HH:mm'" v-model="leaveDate" :show.sync="visibility" :start-date="pickerStartDate" :end-date="pickerEndDate" title="实际驶离时间" placeholder="点击选择"></datetime>
        </div>
      </div>
      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <x-textarea v-model="Memo" :placeholder="'备注'" :max="200" autosize style="color:#888; font-size:16px;"></x-textarea>
        </div>
      </div>


      <div class="displayflex form-btn" v-if="tabNo === 0">
        <div class="flex1" v-on:click="drawAll()">确定提货</div>
        <!-- <div class="flex1 cancel" v-on:click="cancelOrder()">取消订单</div> -->
      </div>

      <div class="displayflex form-btn" v-if="tabNo === 1">
        <div class="flex1" v-on:click="drawRegion()">确定提货</div>
      </div>

      <actionsheet v-model="showDepAddress" :menus="data.depAddressList" show-cancel :cancel-text="'关闭'">
        <p slot="header" v-html="tipD"></p>
      </actionsheet>
      <actionsheet v-model="showArrAddress" :menus="data.arrAddressList" show-cancel :cancel-text="'关闭'">
        <p slot="header" v-html="tipA"></p>
      </actionsheet>
    </div>
  </div>
</template>

<script>
import appHead from '@/components/core/header/app_headbar.vue';
import tools from '../../tools/tool.js';
import { mapState } from "vuex";

export default {
  components:{
    appHead,
  },
  data(){
    return {
      data:{
        ATVNo: '',
        Guid:'',
        routeName: '',
        deliverName:'',
        driver1Name:'',
        totalPkgs:0,
        arrivalAddressCount:0,
        cutomerCount:0,
        depAddressList:[],
        arrAddressList:[],
      },
      datas:{},
      Memo:'',
    
      tabNo: 0,
      showDepAddress:false,
      showArrAddress:false,
      visibility: false,
      leaveDate:'',
      pickerStartDate:'',
      pickerEndDate:'',
      filter: this.$options.filters,
      AreaList:[],
      selectedArea:[],
      selectedTextArea:'',
    }
  },
  watch: {
    selectedArea:{
      handler(n,o){
        if(n.toString() !== o.toString()){
          this.getData();
        }
      },
      deep:true
    },
    tabNo(n,o){
      if(n === 0){
        this.AreaList = [];
        this.selectedArea = [];
        this.selectedTextArea = '';
        this.getData();
      } else {
        this.selectedArea.splice(0,1,this.AreaList[0][0].value);
        this.getData();
      }
    }
  },
  computed: {
    AreaPickerTitle(){
      return `共计${this.AreaList[0].length}个取货地`;
    },
    tipD(){
      return `起始地<br><span class="actitle">共计${this.data.depAddressList.length}个地址</span>`;
    },
    tipA(){
      return `目的地<br><span class="actitle">共计${this.data.arrAddressList.length}个地址</span>`;
    },
    ...mapState({
      pagetitle: state => state.cfg.appBarTitle,
      showstate: state => state.cfg.showAppBar,
    }),
    userinfo(){
      return localStorage.userinfo?JSON.parse(localStorage.userinfo):null
    }
  },
  created(){
    this.leaveDate = tools.getNow(new Date(),'Min', 30, 'YMDHM');
    this.pickerStartDate = tools.getNow(new Date(),'Year', -3, 'YMD');
    this.pickerEndDate = tools.getNow(new Date(),'Year', 3, 'YMD');
    this.getData();
  },
  mounted(){
    
  },
  methods:{
    getData(){
      let query = {
        Guid: this.$route.query.Guid,
        LogState: 51,
        PageIndex:1,
        PageSize:99999,
      }
      if(this.selectedArea.length > 0){
        let arg = JSON.parse(JSON.stringify(this.selectedArea))[0];
        if(typeof(arg) === 'string'){
          arg = arg.split(',');
        }
        query.DepartureProvince = arg[0];
        query.DepartureCity = arg[1];
      }
      this.Ajax.post("SearchPickUpOrders", query).then(resp => {
        if (resp.IsSuccess) {
          this.datas = resp.Datas;

          let depAddr = [],
              arrAddr = [],
              totalPkgs = 0,
              customer = [];

          
          resp.Datas.forEach((x) => {
            let depCode = `${x.DepartureProvince}${x.DepartureCity}${x.DepartureDistrict}${x.DepartureAddress}`,
                depText = `${x.DepartureAddress}`,
                depCodeArr = [x.DepartureProvince, x.DepartureCity, x.DepartureDistrict,x.DepartureAddress],
                arrCode = `${x.ArrivalProvince}${x.ArrivalCity}${x.ArrivalDistrict}${x.ArrivalAddress}`,
                arrText = `${x.ArrivalAddress}`,
                arrCodeArr = [x.ArrivalProvince, x.ArrivalCity, x.ArrivalDistrict,x.ArrivalAddress],
                depItem = {
                  name: depText,
                  label: depText,
                  value: depCodeArr,
                  code: depCode,
                },
                arrItem = {
                  name: arrText,
                  label: arrText,
                  value: arrCodeArr,
                  code: arrCode,
                };
            totalPkgs += x.Pkgs;
            customer.push(x.PickContacts);
            depAddr.push(depItem);
            arrAddr.push(arrItem);
          })
          
          depAddr = this.mapReduce(depAddr, 'code');
          arrAddr = this.mapReduce(arrAddr, 'code');
          customer = [...new Set(customer)];
          if(this.AreaList.length === 0){
            this.AreaList.push(depAddr);
          }
          

          this.data.ATVNo = resp.Datas[0].ATVNo,
          this.data.Guid = resp.Datas[0].Guid,
          this.data.routeName = resp.Datas[0].RouteName,
          this.data.deliverName = resp.Datas[0].DeliverName,
          this.data.driver1Name = resp.Datas[0].Driver1Name,
          this.data.totalPkgs = totalPkgs,
          this.data.arrivalAddressCount = arrAddr.length,
          this.data.cutomerCount = arrAddr.length;//customer.length;
          this.data.depAddressList = depAddr;
          this.data.arrAddressList = arrAddr;

        } else {
          this.Toast({
            message: "列表为空，请稍后刷新"
          });
        }
      });
    },

    drawAll(){
      let query = {
        Guid: this.data.Guid,
        ActualDepartureDate: this.leaveDate,
        Memo: this.Memo,
        PRContactsTel: this.userinfo.MobileTel1,
        State: 52,
      };
      this.Ajax.post("SFYOrderApi", query).then(resp => {
        if(resp.IsSuccess){
          this.Toast({
            message: "操作成功",
          });
          this.$router.go(-1);
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    drawRegion(){
      let query = {
        AtvehicleDetail: this.datas,
        Guid: this.data.Guid,
        ActualDepartureDate: this.leaveDate,
        Memo: this.Memo,
        PRContactsTel: this.userinfo.MobileTel1,
        State: 52,
      }
      this.Ajax.post("SFYOrderApi", query).then(resp => {
        if(resp.IsSuccess){
          this.Toast({
            message: "操作成功",
          });
          this.$router.go(-1);
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    cancelOrder(){
      let _this = this;
      this.$vux.confirm.show({
        content: '确认取消订单？',
        onCancel () {
          return false;
        },
        onConfirm () {
          let query = {
            ATVGuid: _this.$route.query.Guid,
            TenantGuid: _this.userinfo.TenantGuid,
          }
          _this.Ajax.post("RefusalOrder", query).then(resp => {
            if(resp.IsSuccess){
              _this.Toast({
                message: "提货已取消",
                duration: 1000,
              });
              setTimeout(() => { _this.$router.push({ path: '/driver/carDraw' }) }, 1000)
            } else {
              _this.Toast({
                message: resp.ErrorMessage
              });
            }
          });
        }
      })
    },

    getText(e){
      let arg = e[0];
      if(typeof(arg) === 'string'){
        arg = e[0].split(',');
      }
      this.selectedTextArea = `${this.filter.province(arg[0])}${this.filter.city(arg[1])}`;
    },

    mapReduce(arr, keyName){
      let obj = {};
      arr = arr.reduce((item, next) => {
        obj[next[keyName]] ? '' : obj[next[keyName]] = true && item.push(next);
        return item;
      }, []);
      return arr;
    }
  }
}
</script>
